<template>
  <el-upload
    class="avatar-uploader"
    action="https://jsonplaceholder.typicode.com/posts/"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
    :http-request="Upload"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  </el-upload>
</template>
<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<script>
import OSS from 'ali-oss';
const client = new OSS({
  region: 'oss-cn-shanghai',
  accessKeyId: 'LTAIxZYjNPM6pgO3',
  accessKeySecret: '11iG8LcwySD1Ryw8aT1PVrQitMNYUl',
  bucket: 'syg-photo'
})
export default {
  props:['imageUrlCover','ImageType'],
  data(){
    return {
      imageUrl:''
    }
  },
  watch:{
    imageUrlCover:{
      handler (newV, oldV) {
        this.imageUrl = newV
      },
      deep:true
    }
  },
  methods: {
    Upload(file) {
      const that = this
      if(file.file.size / 1024 > 500){
        this.$message.error('请上传不大于500KB的图片文件')
        return false
      }
      let fileName = file.file.name
      let sourceFileName = 'photo-' + fileName + '-' + Date.parse(new Date())
      let uid = file.file.uid
      client.put(sourceFileName, file.file).then(res => {
        this.$set(this.$data,'imageUrl',res.url)
        that.$emit('changeadvertCoverImage', {cover:res.url,type:that.ImageType})
      })
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      if (!file.type.includes('image')) {
        this.$message.error('只能上传图片文件')
        return false
      }
    }
  }
};
</script>